/**
 * Copyright (c) 2015 Baidu. All Rights Reserved.
 *
 * @file 程序入口
 * @author yuanguozheng
 */
var creator = require('./creator');
var program = require('commander');
var config = require('./utils/config');
var fs = require('fs');
var jsonfile = require('jsonfile');
var packager = require('./utils/packager');

program
    .option('-f, --file [path]', 'Parse from file')
    .option('-c, --class [class]', 'Setup root class')
    .option('-t, --tar', 'Need package')
    .parse(process.argv);

if (program.file) { // 使用静态文件
    if (!program.class) {
        console.error('Root class not set.');
    } else if (fs.existsSync(program.file)) {
        var jsonObj = jsonfile.readFileSync(program.file);
        creator.withJsonObject(jsonObj, program.class, function () {
            if (program.tar) {
                packager();
            }
        });
    }
}
else { // 使用request_rules的配置，批量请求
    var reqs = config.requestRules();
    var flag = reqs.length;
    for (var i = 0; i < reqs.length; i++) {
        var cls = reqs[i]['root_cls'];
        var reqModel = reqs[i]['request_model'];
        creator.withRequestModel(reqModel, cls, function () {
            flag--;
            if (flag === 0) {
                packager();
            }
        });
    }
}

